package com.zb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.constant.FieldTypeConstant;
import com.zb.entity.*;
import com.zb.mapper.ZjWorkModuleFieldMapper;
import com.zb.mobile.UserOrderVo;
import com.zb.result.PageUtil;
import com.zb.service.*;
import com.zb.vo.WorkFieldContentVo;
import com.zb.vo.WorkModuleFieldListVo;
import com.zb.vo.WorkModuleFieldSelectVo;
import com.zb.vo.WorkModuleFieldVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 工单模块字段关联表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-09-26
 */
@Service
public class ZjWorkModuleFieldServiceImpl extends ServiceImpl<ZjWorkModuleFieldMapper, ZjWorkModuleField> implements ZjWorkModuleFieldService {
    @Resource
    private ZjWorkModuleFieldMapper workModuleFieldMapper;
    @Resource
    private ZjWorkFieldService workFieldService;
    @Resource
    private ZjWorkFieldContentService workFieldContentService;
    @Resource
    private ZjWorkFieldValService workFieldValService;

    // 新增或修改工单自定义字段
    @Override
    public void save(Long custAccId, Long moduleId, WorkModuleFieldVo moduleFieldVo) {
        Assert.isTrue(null == workModuleFieldMapper.existByWorkFieldId(moduleId, moduleFieldVo.getId(), moduleFieldVo.getWorkFieldId()),  "字段已重复添加关联！");
        ZjWorkModuleField field = new ZjWorkModuleField();
        BeanUtil.copyProperties(moduleFieldVo, field);
        if (null != field.getId()) {
            this.updateById(field);
            return;
        }
        field.setId(IdWorker.getId());
        field.setCustAccId(custAccId);
        field.setModuleId(moduleId);
        this.save(field);
    }

    // 根据工单字段ID获取关联的工单模块名称
    @Override
    public List<ZjWorkModuleField> getByWorkFields(List<Long> workFields) {
        if (null == workFields || workFields.isEmpty()) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjWorkModuleField> wrapper = new QueryWrapper<>();
        wrapper.in("work_field_id", workFields);
       return  this.list(wrapper);
    }

    // 获取工单字段列表
    @Override
    public Map<String, Object> getList(Long moduleId, PageUtil pageUtil) {
        PageUtil.setPageLimit(pageUtil);
        QueryWrapper<ZjWorkModuleField> wrapper = new QueryWrapper<>();
        wrapper.eq("module_id", moduleId);
        Page<ZjWorkModuleField> page = this.page(new Page<>(pageUtil.getPage(), pageUtil.getLimit()), wrapper);
        List<Long> workFieldIds = page.getRecords().stream().map(ZjWorkModuleField::getWorkFieldId).distinct().toList();
        List<ZjWorkField> fields = workFieldService.getByIds(workFieldIds);

        List<WorkModuleFieldListVo> voList = page.getRecords().stream().map(field -> {
            WorkModuleFieldListVo vo = new WorkModuleFieldListVo();
            BeanUtil.copyProperties(field, vo);
            ZjWorkField workField = fields.stream().filter(f -> Objects.equals(f.getId(), field.getWorkFieldId())).findFirst().orElse(null);
            if (null != workField) {
                vo.setName(workField.getName());
                vo.setType(workField.getType());
            }
            vo.setCreateTime(field.getGmtCreate());
            vo.setUpdateTime(field.getGmtUpdate());
            return vo;
        }) .toList();
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList);
    }

    // 根据ID获取工单字段详情
    @Override
    public WorkModuleFieldVo getDetail(Long id) {
        ZjWorkModuleField field = this.getById(id);
        Assert.isTrue(null != field, "工单模块自定义字段ID参数[" + id + "]的数据不存在");

        WorkModuleFieldVo vo = new WorkModuleFieldVo();
        BeanUtil.copyProperties(field, vo);
        return vo;
    }

    // 批量更新字段必填项
    @Override
    public void updateRequiredBatchById(List<Long> ids, boolean required) {
        workModuleFieldMapper.updateRequiredBatchById(ids, required);
    }

    // 批量更新移动显示项
    @Override
    public void updateMobileShowBatchById(List<Long> ids, boolean mobileShow) {
        workModuleFieldMapper.updateMobileShowBatchById(ids, mobileShow);
    }

    // 批量更新是否作为列表查询条件项
    @Override
    public void updateListSelectBatchById(List<Long> ids, boolean listSelect) {
        workModuleFieldMapper.updateListSelectBatchById(ids, listSelect);
    }

    // 批量更新是否在列表展示项
    @Override
    public void updateListShowBatchById(List<Long> ids, boolean listShow) {
        workModuleFieldMapper.updateListShowBatchById(ids, listShow);
    }

    // 批量删除工单模块自定义工单字段
    @Override
    public void deleteBatchById(List<Long> ids) {
        if (null == ids || ids.isEmpty()) {
            return;
        }
        List<Long> workFieldIds =  workFieldValService.getRealtionWorkFieldIdByModuleFieldIds(ids);
        if (CollectionUtils.isNotEmpty(workFieldIds)) {
            QueryWrapper<ZjWorkField> fieldQueryWrapper = new QueryWrapper<>();
            fieldQueryWrapper.select("name");
            fieldQueryWrapper.in("id", workFieldIds);
            String fieldNames = workFieldService.list(fieldQueryWrapper).stream().map(ZjWorkField::getName).collect(Collectors.joining("、"));
            Assert.isTrue(false, "工单字段[" + fieldNames + "]已被使用中，不可删除！");
        }
        this.removeByIds(ids);
    }

    // 根据模块ID获取工单自定义字段
    @Override
    public List<WorkModuleFieldSelectVo> getModuleField(boolean mobile, Long moduleId) {
        QueryWrapper<ZjWorkModuleField> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("is_required");
        wrapper.select("id", "work_field_id", "is_required AS required");
        wrapper.eq("module_id", moduleId);
        List<ZjWorkModuleField> workModuleFields = this.list(wrapper);
        List<Long> workFieldIds = workModuleFields.stream().map(ZjWorkModuleField::getWorkFieldId).distinct().toList();
        List<ZjWorkField> workFieldList = workFieldService.getByIds(workFieldIds);
        List<ZjWorkFieldContent> fieldContentList = workFieldContentService.getByWorkFieldIds(workFieldIds);

        List<WorkModuleFieldSelectVo> voList = new ArrayList<>();
        workModuleFields.forEach(moduleField -> {
            ZjWorkField field = workFieldList.stream().filter(f -> !f.getDisabled() && Objects.equals(f.getId(), moduleField.getWorkFieldId())).findFirst().orElse(null);
            if (null != field) {
                WorkModuleFieldSelectVo vo = new WorkModuleFieldSelectVo();
                BeanUtil.copyProperties(field, vo);
                vo.setModuleFieldId(moduleField.getId());
                vo.setWorkFieldId(field.getId());
                vo.setContents(fieldContentList.stream().filter(f -> Objects.equals(f.getWorkFieldId(), field.getId())).map(con -> {
                    return new WorkFieldContentVo(con.getId(), con.getVal());
                }).toList());
                if (mobile) {
                    if (field.getMobileShow()) voList.add(vo);
                } else {
                    voList.add(vo);
                }
            }
        });
        return voList;
    }

    // 获取工单列表搜索条件的工单自定义搜索字段
    @Override
    public List<SelectResultVo> getOrderListSelectField(Long custAccId) {
        QueryWrapper<ZjWorkModuleField> wrapper = new QueryWrapper<>();
        wrapper.select("work_field_id");
        wrapper.eq("cust_acc_id", custAccId).eq("is_list_select", true);
        List<ZjWorkModuleField> workModuleFields = this.list(wrapper);
        List<Long> workFieldIds = workModuleFields.stream().map(ZjWorkModuleField::getWorkFieldId).distinct().toList();
        return workFieldService.getByIds(workFieldIds)
                .stream()
                .filter(f -> Objects.equals(FieldTypeConstant.FIELD_TYPE_1, f.getType()) || Objects.equals(FieldTypeConstant.FIELD_TYPE_3, f.getType())|| Objects.equals(FieldTypeConstant.FIELD_TYPE_4, f.getType()))
                .map(field -> {
           return new SelectResultVo(field.getId(), field.getName());
        }).toList();
    }

    // 根据工单模块ID获取工单列表显示字段
    @Override
    public List<ZjWorkModuleField> getOrderListShowFieldByModuleIds(List<Long> moduleIds) {
        if (null == moduleIds || moduleIds.isEmpty()) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjWorkModuleField> wrapper = new QueryWrapper<>();
        wrapper.select("id", "module_id", "work_field_id");
        wrapper.eq("is_list_show", true)
                .in("module_id", moduleIds);
        return this.list(wrapper);
    }

    // 获取工单列表表头的工单自定义字段
    @Override
    public List<SelectResultVo> getOrderListTableTitleField(Long custAccId) {
        QueryWrapper<ZjWorkModuleField> wrapper = new QueryWrapper<>();
        wrapper.select("work_field_id");
        wrapper.eq("cust_acc_id", custAccId).eq("is_list_show", true);
        List<ZjWorkModuleField> workModuleFields = this.list(wrapper);
        List<Long> workFieldIds = workModuleFields.stream().map(ZjWorkModuleField::getWorkFieldId).distinct().toList();
        return workFieldService.getByIds(workFieldIds)
                .stream()
                .filter(f -> Objects.equals(FieldTypeConstant.FIELD_TYPE_1, f.getType()) || Objects.equals(FieldTypeConstant.FIELD_TYPE_3, f.getType())|| Objects.equals(FieldTypeConstant.FIELD_TYPE_4, f.getType()))
                .map(field -> {
                    return new SelectResultVo(field.getId(), field.getName());
                }).toList();
    }
}
